/*
* Copyright 2005-2008 Pulse Technologies. Tutti i diritti riservati.
*/
package org.obsidianrad.server.services.user.context;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.object.MappingSqlQuery;

/**
 * Recupera la lista dei contesti dal database
 * 
 * @author Eligio Colutta
 * @version $Rev: 4 $
 * @lastautorcommit $Author: eliosh $
 * @lastdatecommit $Date: 2009-10-31 12:37:28 +0100(sab, 31 ott 2009) $
 */
public class GenericContextManager extends JdbcDaoSupport implements IContextManager {

	private static final String DEF_CONTEXT_LIST = "select id, name from context";
	private MappingSqlQuery contextMapping;
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Integer> getContextIds() {
		List<ObsidianContext> contextList = contextMapping.execute();
		
		List<Integer> retVal = new ArrayList<Integer>();
		for(ObsidianContext oc : contextList){
			retVal.add(oc.getId());
		}
		return retVal;
	}

	@Override
	protected void initDao() throws Exception {
		super.initDao();
		this.contextMapping = new ContextMapping(getDataSource());
	}

    /**
     * Query object to look up a user.
     */
	private class ContextMapping extends MappingSqlQuery {
		protected ContextMapping(DataSource ds) {
			super(ds, DEF_CONTEXT_LIST);
			compile();
		}

		protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
			Integer id = rs.getInt(1);
			String name = rs.getString(2);
			ObsidianContext context = new ObsidianContext(id, name);
			return context;
		}
	}

}
